﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.IO;
using System.Xml;


namespace ECGWeb
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        static ECGService.ECGServiceClient serviceClient = new ECGService.ECGServiceClient();
        static ECGService.HistoryRecord[] recordArray;
        static ECGService.Patient patient;
        static string recordDir;
        ECGService.User user = new ECGService.User();       

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["username"] != null)
            {
                if (!Page.IsPostBack)
                {
                    //Tô đậm nút bấm
                    //Button btn = (Button)Master.FindControl("btn_patientpage");
                    //btn.BackColor = System.Drawing.Color.Gray;

                    user.username = (string)Session["username"];
                    user.realID = (string)Session["realID"];
                    user.permission = (int)Session["permission"];

                    this.loadData(user.realID);

                    this.lbPatientName.Text = patient.patientName;
                    this.lbPatientID.Text = patient.patientID;
                    this.lbBirthDay.Text = patient.dateOfBirth.ToString("dd/MM/yyyy");
                    this.lbSex.Text = patient.sex ? "Nam" : "Nữ";
                }

                if (recordArray != null)
                {
                    this.gridview1.DataSource = recordArray;
                    this.gridview1.DataBind();
                }
                else
                {
                    fakeRecordGridViewData(this.gridview1);
                }
            }
            else
                Response.Redirect("~/HomePage.aspx");                   
        }

        public void loadData(string pid)
        {
            recordArray = serviceClient.getAllRecordByPID(pid);
            patient = serviceClient.getPatientByID(pid);   
        }

        [WebMethod]
        public static string loadECGRecord(string recordID)
        {
            //use service
            return serviceClient.loadECGRecord(recordID);

            #region not use service
            //ECGService.HistoryRecord hr = new ECGService.HistoryRecord();
            //hr = serviceClient.getRecordByID(recordID);
            //FileStream fs = new FileStream(hr.recordDir, FileMode.Open, FileAccess.Read);
            //StreamReader sr = new StreamReader(fs);

            ////Doc tu file cua Trong
            ////string result = "";
            ////string line = sr.ReadLine();
            ////while (line != null)
            ////{
            ////    result += line + "|";
            ////}

            ////Doc tu file Physio
            //sr.ReadLine();
            //sr.ReadLine();
            //string line = sr.ReadLine();
            //string result = "";
            //int i = 1;
            //while (line != null || i < 500) 
            //{
            //    string[] arr = line.Split('\t');
            //    string[] arr1 = arr[0].Split(':');
            //    double time = Convert.ToDouble(arr1[1]);
            //    double mvol = Convert.ToDouble(arr[1]);
            //    int x = (int)(time * 94.488);
            //    int y = (int)(mvol * 37.759);
            //    result = result + x.ToString() + "," + (50 - y).ToString() + ",";
            //    line = sr.ReadLine();
            //    i++;
            //}
            //sr.Close();
            //fs.Close();

            //return result;
            #endregion
        }

        [WebMethod]
        public static string loadECGRecord12(string recordID)
        {
            return serviceClient.loadECGRecord12(recordID);
        }

        [WebMethod]
        public static string loadAFrame(string recordID)
        {
            recordDir = serviceClient.getRecordByID(recordID).recordDir;
            string result = serviceClient.loadAFrameFromRecord(recordDir, 0);
            return result;
        }

        [WebMethod]
        public static string continueLoadAFrame(long offset)
        {
            string result = serviceClient.loadAFrameFromRecord(recordDir, offset);
            return result;
        }

        protected void gridview1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gridview1.PageIndex = e.NewPageIndex;            
            this.gridview1.DataBind();
        }

        protected void fromDateTxtBox_TextChanged(object sender, EventArgs e)
        {
            DateTime fromDate = new DateTime();
            DateTime toDate = new DateTime();

            if (DateTime.TryParse(this.toDateTxtBox.Text, out toDate))
            {
                if (DateTime.TryParse(this.fromDateTxtBox.Text, out fromDate))
                {
                    if (toDate >= fromDate)
                    {
                        //toDate.AddDays(1);
                        //Array.Clear(recordArray, 0, recordArray.Length);
                        recordArray = serviceClient.getRecordByPIDBetween(patient.patientID, fromDate, toDate);

                        if (recordArray != null)
                        {
                            this.gridview1.DataSource = recordArray;
                            this.gridview1.DataBind();
                        }
                        else
                        {
                            fakeRecordGridViewData(this.gridview1);
                        }

                        if (recordArray == null || recordArray.Length == 0)
                            notifyLbl.Text = "Không có bản ghi nào trong khoảng thời gian trên";
                        else
                            notifyLbl.Text = "";
                    }
                    else
                        notifyLbl.Text = "Bạn đang chọn từ ngày nhỏ hơn đến ngày! Vui lòng nhập chính xác!";
                }
            }
        }        

        protected void toDateTxtBox_TextChanged(object sender, EventArgs e)
        {
            DateTime fromDate = new DateTime();
            DateTime toDate = new DateTime();

            if (DateTime.TryParse(this.toDateTxtBox.Text, out toDate))
            {
                if (DateTime.TryParse(this.fromDateTxtBox.Text, out fromDate))
                {
                    if (toDate >= fromDate)
                    {
                        //toDate.AddDays(1);
                        recordArray = serviceClient.getRecordByPIDBetween(patient.patientID, fromDate, toDate);

                        if (recordArray != null)
                        {
                            this.gridview1.DataSource = recordArray;
                            this.gridview1.DataBind();
                        }
                        else
                        {
                            fakeRecordGridViewData(this.gridview1);
                        }

                        if (recordArray == null || recordArray.Length == 0)
                            notifyLbl.Text = "Không có bản ghi nào trong khoảng thời gian trên";
                        else
                            notifyLbl.Text = "";
                    }
                    else
                        notifyLbl.Text = "Bạn đang chọn từ ngày nhỏ hơn đến ngày! Vui lòng nhập chính xác!";
                }
            }
        }

        public void fakeRecordGridViewData(GridView gridview)
        {
            ECGService.HistoryRecord[] historyRecordArrayFake = new ECGService.HistoryRecord[1];
            historyRecordArrayFake[0] = new ECGService.HistoryRecord();
            historyRecordArrayFake[0].recordID = "fake";
            historyRecordArrayFake[0].dateTimeOfRecord = DateTime.Now;

            gridview.DataSource = historyRecordArrayFake;
            gridview.DataBind();
            gridview.Rows[0].Visible = false;
            gridview.Rows[0].Controls.Clear();
        }

        public void showMessage(string text)
        {
            string strBuilder = "<script language='javascript'>alert('" + text + "')</script>";
            Response.Write(strBuilder);
        }
    }
}